<?php

namespace app\model;

use think\Model;

class UserOauth extends Model
{
    // 表名
    protected $name = 'user_oauth';

    // 自动时间戳
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    // 字段类型转换
    protected $type = [
        'extra_data' => 'json',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'expires_at' => 'datetime',
    ];

    // 隐藏字段
    protected $hidden = ['access_token', 'refresh_token'];

    // 关联用户
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // 通过平台和openid查找
    public static function findByPlatformOpenid($platform, $openid)
    {
        return self::where('platform', $platform)
            ->where('openid', $openid)
            ->find();
    }

    // 通过平台和unionid查找
    public static function findByPlatformUnionid($platform, $unionid)
    {
        return self::where('platform', $platform)
            ->where('unionid', $unionid)
            ->find();
    }

    // 检查用户是否已绑定该平台
    public static function checkUserBound($userId, $platform)
    {
        return self::where('user_id', $userId)
            ->where('platform', $platform)
            ->find();
    }

    // 更新token
    public function updateToken($accessToken, $refreshToken = null, $expiresIn = 7200)
    {
        $this->access_token = $accessToken;
        if ($refreshToken) {
            $this->refresh_token = $refreshToken;
        }
        $this->expires_at = date('Y-m-d H:i:s', time() + $expiresIn);
        return $this->save();
    }

    // 检查token是否过期
    public function isTokenExpired()
    {
        if (!$this->expires_at) {
            return false;
        }
        return strtotime($this->expires_at) <= time();
    }
}